package org.water.garden.view;

import java.util.Date;

import org.water.garden.R;

import android.content.Context;
import android.database.Cursor;
import android.provider.Im;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

public class MessageListAdapter extends ResourceCursorAdapter {

	public MessageListAdapter(Context context, Cursor c) {
		super(context, R.layout.message_list_row, c);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		//Message body text view
		String body = cursor.getString(cursor.getColumnIndex(Im.MessagesColumns.BODY));
		
		TextView textView = ((TextView)view.findViewById(android.R.id.text1));
		textView.setText(body);

		int type = cursor.getInt(cursor.getColumnIndex(Im.MessagesColumns.TYPE));
		
		LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		
		switch (type) {
		case Im.MessageType.OUTGOING:
			textView.setTextColor(context.getResources().getColor(R.color.msg_outcome));
			params.addRule(RelativeLayout.ALIGN_WITH_PARENT_RIGHT, RelativeLayout.TRUE);
			break;
		case Im.MessageType.INCOMING:
			textView.setTextColor(context.getResources().getColor(R.color.msg_income));
			params.addRule(RelativeLayout.ALIGN_WITH_PARENT_LEFT, RelativeLayout.TRUE);
		default:
			break;
		}
		
		if(cursor.getInt(cursor.getColumnIndex(Im.MessagesColumns.SHOW_TIME_STAMP)) == 0){
			cursor.updateInt(cursor.getColumnIndex(Im.MessagesColumns.SHOW_TIME_STAMP), new Long((new Date()).getTime()).intValue());
			cursor.commitUpdates();
		}
		
		textView.setLayoutParams(params);
	}
}